package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.UserMemberVo;
import com.atguigu.gulimall.seckill.feign.CouponFeign;
import com.atguigu.gulimall.seckill.feign.ProductFeign;
import com.atguigu.gulimall.seckill.interceptor.SeckillInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SkuInfoRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSku;
import com.atguigu.gulimall.seckill.vo.SeckillSku;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Resource
    CouponFeign couponFeign;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedissonClient redissonClient;
    @Resource
    ProductFeign productFeign;
    @Resource
    RabbitTemplate rabbitTemplate;

    private final  String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final  String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHONE = "seckill:stock:"; //+ 商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R session = couponFeign.getLatest3DaySession();
        if(session.getCode()==0){
            //查找上架商品信息
            List<SeckillSessionWithSku> sessionData = session.getData("data", new TypeReference<List<SeckillSessionWithSku>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(sessionData);
            //2.缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    @Override
    public List<SkuInfoRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次，
        long time = System.currentTimeMillis();

        Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long endTime = Long.parseLong(s[1]);
            if(time>=start && time<=endTime){
                List<String> range = stringRedisTemplate.opsForList().range(key, 0, -1);
                BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);
                if(list!=null){
                    List<SkuInfoRedisTo> collect = list.stream().map(item -> {
                        SkuInfoRedisTo redisTo = JSON.parseObject(item.toString(), SkuInfoRedisTo.class);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SkuInfoRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys!=null&&keys.size()>0){
            String regx = "\\d_"+skuId;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String json = ops.get(key);
                    SkuInfoRedisTo redisTo = JSON.parseObject(json, SkuInfoRedisTo.class);
                    if(System.currentTimeMillis()>=redisTo.getStartTime()&&System.currentTimeMillis()<=redisTo.getEndTime()){

                    }else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        UserMemberVo memberVo = SeckillInterceptor.loginUser.get();

        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if(StringUtils.isNotBlank(json)){
            SkuInfoRedisTo redisTo = JSON.parseObject(json, SkuInfoRedisTo.class);
            //1.检验时间的合理性
            if (System.currentTimeMillis() >= redisTo.getStartTime() && System.currentTimeMillis() <= redisTo.getEndTime()) {
                //2、检验随机码和商品id
                String randomCode = redisTo.getRandomCode();
                //3、检验随机码和商品id&&验证购物数量是否合理
                if(key.equals(randomCode)&&num<=redisTo.getSeckillLimit().intValue()){
                    String redisKey = memberVo.getId() + "_" + killId;
                    Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(),redisTo.getEndTime()-System.currentTimeMillis(), TimeUnit.MILLISECONDS);
                    if (absent) {
                        //成功 说明从来没买过
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHONE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            //秒杀成功
                            //快速下单 发送mq消息
                            if(b){
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setMemberId(memberVo.getId());
                                orderTo.setNum(num);
                                orderTo.setOrderSn(timeId);
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                orderTo.setSkuId(redisTo.getSkuId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                return timeId;
                            }
                    }
                }
            } else {
                redisTo.setRandomCode(null);
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSku> sessionData) {
        if(sessionData!=null&&sessionData.size()>0){
            sessionData.stream().forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime+"_"+endTime;
                Boolean hasKey = stringRedisTemplate.hasKey(key);
                if(!hasKey){
                    //缓存活动信息
                    List<String> collect = session.getRelationEntityList().stream().map(item -> item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                    stringRedisTemplate.opsForList().leftPushAll(key,collect);
                }


            });
        }else {
            throw new RRException("没有待上架的秒杀商品，请在后台添加");
        }

    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSku> sessionData) {
        sessionData.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationEntityList().stream().forEach(seckillSku -> {
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                if(!ops.hasKey(seckillSku.getPromotionSessionId().toString()+"_"+seckillSku.getSkuId().toString())){
                    //缓存商品
                    SkuInfoRedisTo redisTo = new SkuInfoRedisTo();
                    //1.sku的基本数据
                    R r = productFeign.skuInfo(seckillSku.getSkuId());
                    if(r.getCode()==0){
                        SkuInfoVo infoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(infoVo);
                    }

                    //2. sku 的秒杀信息
                    BeanUtils.copyProperties(seckillSku,redisTo);

                    //3.设置上当前商品的秒杀时间信息

                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4.随机码

                    redisTo.setRandomCode(token);

                    //5使用库存作为分布式的信号量 限流：
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHONE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSku.getSeckillCount().intValue());
                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSku.getPromotionSessionId().toString()+"_"+seckillSku.getSkuId().toString(),jsonString);
                }
            });
        });

    }

//    @Transactional
//    public void testA() throws Exception {
//        SeckillService seckillService = (SeckillService)AopContext.currentProxy();
//        seckillService.testB();
//    }
//
//    @Transactional
//    public void testB() throws Exception {
//       throw new Exception();
//    }
    public static List<Map<String,Object>> merge(List<Map<String,Object>> m1,List<Map<String,Object>> m2,String string){
        m1.addAll(m2);
        Set<String> set = new HashSet<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        mapList.add(new HashMap<String,Object>(){{
            put(string,11);
        }});

        //Map<String,Object> m   m.get(string)  获得key 为Object  value为 List<Map<String, Object>>  Map
        Map<Object, List<Map<String, Object>>> listMap = m1.stream().collect(Collectors.groupingBy(o -> {
            set.addAll(o.keySet());
            return o.get(string);
        }));

        List<Map<String, Object>> collect = listMap.entrySet().stream().map(o -> {
            Stream<Map.Entry<String, Object>> entryStream = o.getValue().stream().flatMap(m -> {
                Stream<Map.Entry<String, Object>> stream = m.entrySet().stream();
                return stream;
            });
            Map<String, Object> map = entryStream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
            set.stream().forEach(k -> {
                if (!map.containsKey(k)) {
                    map.put(k, 0);
                }
            });
            return map;
        }).collect(Collectors.toList());

        return collect;
    }

}
